require 'digest/sha2'
class User < ActiveRecord::Base
  attr_accessible :username, :password, :email

=begin
DEPENDENCIES WITH OTHER TABLES
  has_and_belongs_to_many :pages
  #traversing a rich association
  has_many :section_edits
  has_many :sections, :through => :section_edits
=end

  #ACCESORS
  attr_accessor :password  #getter / setter


  #VALIDATION
  validates :username, :length => { :within => 3..25 }, :uniqueness => true
  validates_length_of :password, :within => 3..25, :on => :create

  #CALLBACK of DB running
  before_save :create_hashed_password
  after_save :clear_password

  #Advanced query with input params
  scope :sorted, order("users.username ASC")

  attr_protected :hashed_password
  attr_protected :salt

  def name
    "#{username}"
  end

  #static methods
  def self.authenticate(username="", password="")
    user = User.find_by_username(username)
    if user && user.password_match?(password)
      return user
    else
      return false
    end
  end

  def password_match?(password="")
    hashed_password == User.hash_with_salt(password, salt)
  end

  def self.make_salt(username="")
    Digest::SHA2.hexdigest("Use #{username} with #{Time.now} to make salt")
  end

  def self.hash_with_salt(password="", salt="")
    Digest::SHA2.hexdigest("Put #{salt} on the #{password}")
  end

  private

  def create_hashed_password
    # Whenever :password has a value hashing is needed
    unless password.blank?
      # always use "self" when assigning values
      self.salt = User.make_salt(username) if salt.blank?
      self.hashed_password = User.hash_with_salt(password, salt)
    end
  end

  def clear_password
    self.password = nil
  end

end
